Page({
  /**
   * 页面的初始数据
   */
  data: {
    fmList: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    isLoading: false,
    isPlaying: false,
    innerAudioContext: null, // 音频上下文
    currentAudioIndex: -1 // 当前正在播放的音频在列表中的索引
  },
  playAudio(e) {
    const index = e.currentTarget.dataset.index;
    const audio = this.data.fmList[index].faudio;

    if (!this.data.innerAudioContext) {
      this.data.innerAudioContext = wx.createInnerAudioContext();
    }

    if (this.data.currentAudioIndex === index) {
      // 点击的是当前正在播放的音频
      if (!this.data.innerAudioContext.paused) {
        this.data.innerAudioContext.pause();
        this.setData({ isPlaying: false });
      } else {
        this.data.innerAudioContext.play();
        this.setData({ isPlaying: true });
      }
    } else {
      // 点击的是新的音频
      if (this.data.currentAudioIndex !== -1) {
        this.data.innerAudioContext.stop();
      }
      this.data.innerAudioContext.src = audio;
      this.data.innerAudioContext.play();
      this.setData({
        currentAudioIndex: index,
        isPlaying: true
      });
    }
  },

  getData() {
    this.setData({ isLoading: true });

    // 显示加载中
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    });

    let that = this;
    wx.request({
      url: ' http://localhost:8888/fm',
      success(res) {
        console.log(res);
        that.setData({
          fmList: [...that.data.fmList, ...res.data.data.list],
          total: res.data.data.total
        });
      },
      complete() {
        // 手动关闭下拉刷新
        wx.stopPullDownRefresh();
        // 手动关闭加载提示框
        wx.hideLoading();
        // 释放节流阀
        that.setData({ isLoading: false });
      }
    });
  },

  onLoad(options) {
    // 当页面加载完毕的时候，获取列表数据
    this.getData();
  },

  onPullDownRefresh() {
    // 刷新恢复初始值
    this.setData({
      fmList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0
    });
    // 重新查询
    this.getData();
  },

  onReachBottom() {
    if (this.data.isLoading) return;

    this.setData({ pageNum: this.data.pageNum + 1 });

    if (this.data.pageNum > Math.ceil(this.data.total / this.data.pageSize)) {
      wx.showToast({
        title: '没有更多数据了!',
        icon: 'error'
      });
      return;
    }

    this.getData();
  }
});
